<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    private $_id;
    private $_isAdmin;
    private $_idSituacao;
    const ERROR_BLOCKED = 200;
    const ERROR_INACTIVATED = 201;

    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     * 
     * $users = array(
      // username => password
      'demo' => 'demo',
      'admin' => 'admin',
      );
     */
    public function authenticate() {
        $mail = Usuario::model()->getEmailComDominio($this->username);
        $record = Usuario::model()->findByAttributes(array(
            'TX_EMAIL' => $mail
                ));

        if ($record === null) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else if ($record->TX_SENHA !== md5($this->password)) {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        } else if ($record->ID_SITUACAO == Situacao_Usuario::BLOQUEADO) {
            $this->errorCode = self::ERROR_BLOCKED;
        } else if ($record->ID_SITUACAO == Situacao_Usuario::EMAIL_NAO_CONFIRMADO) {
            $this->errorCode = self::ERROR_INACTIVATED;
        } else {
            $this->_id = $record->ID_USUARIO;
            $this->_isAdmin = $record->ID_PERFIL == Perfil_Usuario::ADMINISTRADOR ? true : false;
            $this->_idSituacao = $record->ID_SITUACAO;
            $this->setState('title', $this->username);
            $this->setState('identity', $this);
            $this->errorCode = self::ERROR_NONE;
        }
        return!$this->errorCode;
    }

    public function getId() {
        return $this->_id;
    }

    public function isAdmin() {
        return $this->_isAdmin;
    }

    public function getSituacao() {
        return $this->_idSituacao;
    }

}